<template>
  <el-drawer
    :model-value="visible"
    title="创建公会"
    direction="rtl"
    size="700px"
    :before-close="handleClose"
    @update:model-value="(val) => emit('update:visible', val)"
  >
    <div class="create-union-content">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="create-union-form"
      >
        <el-form-item label="公会头像" prop="avatar">
          <el-input
            v-model="formData.avatar"
            placeholder="请输入头像URL"
            clearable
          />
          <div class="avatar-preview" v-if="formData.avatar">
            <el-image
              :src="formData.avatar"
              fit="cover"
              style="width: 80px; height: 80px; border-radius: 8px; margin-top: 8px;"
              :preview-src-list="[formData.avatar]"
            />
          </div>
        </el-form-item>
        
        <el-form-item label="公会昵称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入公会昵称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="绑定会长" prop="ownerUserNo">
          <el-input
            v-model="formData.ownerUserNo"
            placeholder="请输入会长用户编号"
            clearable
            @blur="handleValidateOwner"
            :class="{ 'is-error': ownerValidationError }"
          />
          <div v-if="ownerValidationError" class="validation-error">
            {{ ownerValidationError }}
          </div>
          <div v-if="ownerValidating" class="validating-text">
            正在验证用户信息...
          </div>
          <div v-if="ownerInfo && ownerValidationSuccess" class="owner-info">
            <div class="owner-info-header">
              <el-icon><Check /></el-icon>
              <span>用户验证成功</span>
            </div>
            <div class="owner-info-content">
              <div class="info-row">
                <span class="label">昵称:</span>
                <span class="value">{{ ownerInfo.nickname }}</span>
              </div>
              <div class="info-row">
                <span class="label">用户编号:</span>
                <span class="value">{{ ownerInfo.userNo }}</span>
              </div>
              <div class="info-row" v-if="ownerInfo.goodNo">
                <span class="label">靓号:</span>
                <span class="value">{{ ownerInfo.goodNo }}</span>
              </div>
              <div class="info-row">
                <span class="label">状态:</span>
                <span class="value" :class="getUserStatusClass(ownerInfo.userStatus)">
                  {{ getUserStatusText(ownerInfo.userStatus) }}
                </span>
              </div>
            </div>
          </div>
        </el-form-item>
        

        
        <el-form-item label="联系方式" prop="phone">
          <el-input
            v-model="formData.phone"
            placeholder="请输入联系方式"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="公告/宣言" prop="announcement">
          <el-input
            v-model="formData.announcement"
            type="textarea"
            :rows="4"
            placeholder="请输入公告或宣言内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          完成
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Check } from '@element-plus/icons-vue'
import { unionCreateApi } from '@/api/union'
import { checkUserNoApi } from '@/api/user'

interface Props {
  visible: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)

// 会长ID校验相关
const ownerValidating = ref(false)
const ownerValidationError = ref('')
const ownerValidationSuccess = ref(false)
const ownerInfo = ref<any>(null)

const formData = reactive({
  name: '',
  avatar: 'https://res.wadichat.com/avatar/wadi-default-union.jpg',
  ownerUserNo: '',
  phone: '',
  announcement: ''
})

const formRules: FormRules = {
  name: [
    { required: true, message: '请输入公会昵称', trigger: 'blur' },
    { min: 1, max: 50, message: '公会昵称长度在1-50个字符', trigger: 'blur' }
  ],
  ownerUserNo: [
    { required: true, message: '请输入会长用户编号', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系方式', trigger: 'blur' }
  ],
  announcement: [
    { max: 500, message: '公告内容不能超过500个字符', trigger: 'blur' }
  ]
}

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 新增模式，清空表单
    Object.assign(formData, {
      name: '',
      avatar: 'https://res.wadichat.com/avatar/wadi-default-union.jpg',
      ownerUserNo: '',
      phone: '',
      announcement: ''
    })
    // 清空校验状态
    ownerValidationError.value = ''
    ownerValidationSuccess.value = false
    ownerInfo.value = null
  }
})

const handleClose = () => {
  emit('update:visible', false)
  formRef.value?.clearValidate()
  // 清空校验状态
  ownerValidationError.value = ''
  ownerValidationSuccess.value = false
  ownerInfo.value = null
}

// 校验会长ID
const handleValidateOwner = async () => {
  const ownerUserNo = formData.ownerUserNo?.trim()
  
  if (!ownerUserNo) {
    ownerValidationError.value = ''
    ownerValidationSuccess.value = false
    return
  }
  
  // 如果已经校验过且成功，不再重复校验
  if (ownerValidationSuccess.value) {
    return
  }
  
  try {
    ownerValidating.value = true
    ownerValidationError.value = ''
    
    // 调用后端接口校验用户是否存在
    const response = await checkUserNoApi(ownerUserNo)
    if (response.code === 200) {
      ownerValidationSuccess.value = true
      ownerValidationError.value = ''
      ownerInfo.value = response.data
      ElMessage.success('用户验证成功')
    } else {
      ownerValidationError.value = '用户不存在，请检查用户编号'
      ownerValidationSuccess.value = false
      ownerInfo.value = null
    }
    
  } catch (error: any) {
    ownerValidationError.value = error.message || '校验失败，请重试'
    ownerValidationSuccess.value = false
  } finally {
    ownerValidating.value = false
  }
}

// 获取用户状态文本
const getUserStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '正常'
    case 1:
      return '封禁'
    case 2:
      return '注销'
    default:
      return '未知'
  }
}

// 获取用户状态样式类
const getUserStatusClass = (status: number) => {
  switch (status) {
    case 0:
      return 'status-normal'
    case 1:
      return 'status-banned'
    case 2:
      return 'status-cancelled'
    default:
      return 'status-unknown'
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 检查会长ID校验状态
    if (formData.ownerUserNo && !ownerValidationSuccess.value) {
      ElMessage.warning('请先验证会长用户编号')
      return
    }
    
    loading.value = true
    
    // 构建提交数据
    const submitData = {
      name: formData.name,
      avatar: formData.avatar,
      ownerUserNo: formData.ownerUserNo,
      phone: formData.phone,
      announcement: formData.announcement
    }
    
    await unionCreateApi(submitData)
    
    ElMessage.success('创建成功')
    emit('success')
    handleClose()
  } catch (error: any) {
    ElMessage.error(error.message || '创建失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.create-union-content {
  padding: 20px;
}

.create-union-form {
  .el-form-item {
    margin-bottom: 24px;
  }
}

.avatar-preview {
  margin-top: 8px;
}



.drawer-footer {
  text-align: right;
  padding: 20px;
  border-top: 1px solid #e4e7ed;
}

:deep(.el-form-item__label) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-input__inner) {
  font-size: 16px;
}

:deep(.el-textarea__inner) {
  font-size: 16px;
}

:deep(.el-drawer__header) {
  font-size: 18px;
  font-weight: 600;
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-drawer__body) {
  padding: 0;
}

.unit-text {
  margin-left: 8px;
  color: #909399;
  font-size: 14px;
}

.validation-error {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
  line-height: 1.4;
}

.validating-text {
  color: #409eff;
  font-size: 12px;
  margin-top: 4px;
  line-height: 1.4;
}

:deep(.is-error) {
  .el-input__inner {
    border-color: #f56c6c;
  }
}

.owner-info {
  margin-top: 12px;
  padding: 12px;
  background: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 6px;
  
  .owner-info-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    color: #67c23a;
    font-weight: 500;
    
    .el-icon {
      margin-right: 6px;
      font-size: 16px;
    }
  }
  
  .owner-info-content {
    .info-row {
      display: flex;
      margin-bottom: 4px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .label {
        min-width: 70px;
        color: #606266;
        font-size: 13px;
      }
      
      .value {
        color: #303133;
        font-size: 13px;
        font-weight: 500;
        
        &.status-normal {
          color: #67c23a;
        }
        
        &.status-banned {
          color: #f56c6c;
        }
        
        &.status-cancelled {
          color: #909399;
        }
        
        &.status-unknown {
          color: #e6a23c;
        }
      }
    }
  }
}
</style> 